import { useContext, useState, useEffect, useRef } from 'react';
import { GlobalContext, emitter } from './context';
import { useForceUpdate } from './useForceUpdate';

function isEqual(newState, oldState){
    if ( newState === oldState ) {
        return true;
    }
    return false;
}
export const useSelector = (selector)=>{
    const forceUpdate = useForceUpdate();
    const store = useContext(GlobalContext);
    const latestSelector = useRef(selector);
    const latestSelectedState = useRef(selector(store.getState()));
    if ( !store ) {
        throw new Error('useSelector Hook必须在Provider内使用');
    }
    // latestSelector.current = selector;
    // latestSelectedState.current = selector(storeRef.current.getState());
    useEffect(()=>{
        const checkForUpdates = (newStore)=>{            
            const newSelectedState = latestSelector.current(newStore);
            // 只有当指定获取的State状态变化时，才触发render
            // console.log('new State...');
            // console.log(newSelectedState);
            // console.log(latestSelectedState.current);
            if ( !isEqual(newSelectedState, latestSelectedState.current)) {
                console.log('update.....')
                console.log('-------');
                // storeRef.current = { ...store, getState:()=>newStore };
                latestSelectedState.current = newSelectedState;
                forceUpdate();
                
            }
        }
        emitter.on('stateChange', checkForUpdates);
        return ()=>{
            emitter.off('stateChange', checkForUpdates);
        }
    },[])
    return [latestSelectedState.current, store.dispatch];
}